package cn.signalpha.modules.shop.service;

import cn.signalpha.core.tool.jackson.JsonUtil;
import cn.signalpha.modules.shop.entity.OrderDetail;
import cn.signalpha.modules.shop.mapper.OrderDetailMapper;
import cn.signalpha.modules.shop.vo.OrderGoodsVO;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import lombok.AllArgsConstructor;
import org.springframework.cache.annotation.CacheEvict;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.stereotype.Service;

import java.util.List;

import static cn.signalpha.common.cache.CacheNames.EXPIRATION_TIME_7;
import static cn.signalpha.common.cache.CacheNames.ORDER_DETAIL;


/**
 * 订单详情 服务类
 *
 * @author suguangjun
 */
@Service
@AllArgsConstructor
public class OrderDetailService extends ServiceImpl<OrderDetailMapper, OrderDetail> {

	/**
	 * 订单号查询
	 */
	public List<OrderDetail> getByOrderNo(String orderNo) {
		return baseMapper.selectList(Wrappers.<OrderDetail>lambdaQuery().eq(OrderDetail::getOrderNo, orderNo));
	}

	/**
	 * 是否有处于售后的商品
	 */
	public boolean isExistRefundStatus1(String orderNo) {
		return baseMapper.selectCount(Wrappers.<OrderDetail>lambdaQuery().eq(OrderDetail::getOrderNo, orderNo).eq(OrderDetail::getRefundStatus, 1)) > 0;
	}

	/**
	 * 根据订单号搜索
	 */
	@Cacheable(cacheNames = ORDER_DETAIL + EXPIRATION_TIME_7, key = "#orderNo", unless="#result==null")
	public List<OrderDetail> listByOrderNo(String orderNo) {
		List<OrderDetail> orderDetailList = baseMapper.selectList(
			Wrappers.<OrderDetail>lambdaQuery().eq(OrderDetail::getOrderNo, orderNo)
		);
		orderDetailList.forEach(orderDetail -> {
			orderDetail.setGoods(JsonUtil.parse(orderDetail.getGoodsDetail(), OrderGoodsVO.class));
		});
		return orderDetailList;
	}

	/**
	 * 删除订单详情缓存
	 */
	@CacheEvict(cacheNames = ORDER_DETAIL, key = "#orderNo")
	public void removeCacheByOrderNo(String orderNo) {
	}

	/**
	 * 删除订单详情
	 */
	@CacheEvict(cacheNames = ORDER_DETAIL, key = "#orderNo")
	public void removeByOrderNo(String orderNo) {
		baseMapper.delete(Wrappers.<OrderDetail>lambdaQuery().eq(OrderDetail::getOrderNo, orderNo));
	}
}
